package com.authine.cloudpivot.app.openapi.config;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.gateway.config.LoadBalancerProperties;
import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.Objects;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;

/**
 * @author carter
 * create_date  2020/11/4 10:39
 * description
 */
@Component("loadBalancerClientFilter")
public class LocalDebugLoadBalancerClientFilter extends LoadBalancerClientFilter {

    private final LocalDebugLoadBalancerClient localDebugLoadBalancerClient;

    public LocalDebugLoadBalancerClientFilter(LocalDebugLoadBalancerClient localDebugLoadBalancerClient, LoadBalancerProperties properties) {
        super(localDebugLoadBalancerClient, properties);
        this.localDebugLoadBalancerClient = localDebugLoadBalancerClient;
    }

    @Override
    protected ServiceInstance choose(ServerWebExchange exchange) {

        String serviceId = ((URI) Objects.requireNonNull(exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR))).getHost();

        return localDebugLoadBalancerClient.choose(serviceId, exchange);

    }

}
